$(function () {
    $.util.namespace("$.mainpage.layout");
    $.util.namespace("$.mainpage.mainTabs");
    $.util.namespace("$.mainpage.northToolbar");
    $.util.namespace("$.mainpage.westTree");
    $.util.namespace("$.mainpage.southPanel");
    $.util.namespace("$.mainpage.favoTree");

    var mainTabs = "#layout_center_tabs";
    var centerLayout;

    //  添加一个新的模块选项卡；该方法重载方式如下：
    //      function (tabOption)
    //      function (href)
    //      function (title, href)
    //      function (title, href, iconCls)
    //      function (title, href, iconCls, iniframe)
    //      function (title, href, iconCls, iniframe, closable)
    //      function (title, href, iconCls, iniframe, closable, refreshable)
    //      function (title, href, iconCls, iniframe, closable, refreshable, selected)

    $.mainpage.mainTabs.addModule = function (title, href, iconCls, iniframe, closable, refreshable, selected) {
        var opts = $.mainpage.mainTabs.parseCreateTabArgs(arguments),
            isExists = $.mainpage.mainTabs.isExists(opts.title, opts.href);
        switch (isExists) {
            case 0:
                $.mainpage.mainTabs.createTab(opts);
                break;
            case 1:
                $.mainpage.mainTabs.createTab(opts);
                break;
            case 2:
                $.mainpage.mainTabs.jumeTab(opts.title);
                break;
            default:
                break;
        }
        $.mainpage.mainTabs.target = $(mainTabs);
    };

    $.mainpage.mainTabs.jumeTab = function (which) {
        $(mainTabs).tabs("select", which);
    };

    $.mainpage.mainTabs.tabDefaultOption = {
        title: "新建选项卡",
        href: "",
        iniframe: true,
        closable: true,
        refreshable: true,
        refreshIcon: true,
        iconCls: "icon-standard-application-form",
        repeatable: true,
        selected: true
    };

    //  判断指定的选项卡是否存在于当前主页面的选项卡组中；
    //  返回值：返回的值可能是以下几种：
    //      0:  表示不存在于当前选项卡组中；
    //      1:  表示仅 title 值存在于当前选项卡组中；
    //      2:  表示 title 和 href 都存在于当前选项卡组中；
    $.mainpage.mainTabs.isExists = function (title, href) {
        var t = $(mainTabs), tabs = t.tabs("tabs"), array = $.array.map(tabs, function (val) {
            return val.panel("options");
        }), list = $.array.filter(array, function (val) {
            return val.title == title;
        }), ret = list.length ? 1 : 0;
        if (ret && $.array.some(list, function (val) {
                return val.href == href;
            })) {
            ret = 2;
        }
        return ret;
    };

    $.mainpage.mainTabs.createTab = function (title, href, iconCls, iniframe, closable, refreshable, selected) {
        var t = $(mainTabs), i = 0, opts = $.mainpage.mainTabs.parseCreateTabArgs(arguments);
        while (t.tabs("getTab", opts.title + (i ? String(i) : ""))) {
            i++;
        }
        t.tabs("add", opts);
    };
    $.mainpage.mainTabs.parseCreateTabArgs = function (args) {
        var ret = {};
        if (!args || !args.length) {
            $.extend(ret, $.mainpage.mainTabs.tabDefaultOption);
        } else if (args.length == 1) {
            $.extend(ret, $.mainpage.mainTabs.tabDefaultOption, typeof args[0] == "object" ? args[0] : {
                href: args[0]
            });
        } else if (args.length == 2) {
            $.extend(ret, $.mainpage.mainTabs.tabDefaultOption, {
                title: args[0],
                href: args[1]
            });
        } else if (args.length == 3) {
            $.extend(ret, $.mainpage.mainTabs.tabDefaultOption, {
                title: args[0],
                href: args[1],
                iconCls: args[2]
            });
        } else if (args.length == 4) {
            $.extend(ret, $.mainpage.mainTabs.tabDefaultOption, {
                title: args[0],
                href: args[1],
                iconCls: args[2],
                iniframe: args[3]
            });
        } else if (args.length == 5) {
            $.extend(ret, $.mainpage.mainTabs.tabDefaultOption, {
                title: args[0],
                href: args[1],
                iconCls: args[2],
                iniframe: args[3],
                closable: args[4]
            });
        } else if (args.length == 6) {
            $.extend(ret, $.mainpage.mainTabs.tabDefaultOption, {
                title: args[0],
                href: args[1],
                iconCls: args[2],
                iniframe: args[3],
                closable: args[4],
                refreshable: args[5]
            });
        } else if (args.length >= 7) {
            $.extend(ret, $.mainpage.mainTabs.tabDefaultOption, {
                title: args[0],
                href: args[1],
                iconCls: args[2],
                iniframe: args[3],
                closable: args[4],
                refreshable: args[5],
                selected: args[6]
            });
        }
        return ret;
    };
    $.mainpage.addModuleTab = function (node) {
        var n = node || {}, attrs = node.attributes || {}, opts = $.extend({}, n, {
            title: n.text
        }, attrs);
        opts.href = opts.href ? opts.href : opts.src ? opts.src : '';
        if (!opts.href) {
            if ($.mainpage.westTree.target) {
                $.mainpage.westTree.target.tree('expand', node.target);
            }
            return;
        }
        if (opts.href.indexOf("link/") >= 0) {
            opts.href = opts.href.substring("link/".length, opts.href.length);
            opts.href = $.util.getRootPath() + '/' + opts.href;
        }
        $.mainpage.mainTabs.addModule(opts);
    };

    $.mainpage.westTree.initTree = function () {
        $.mainpage.westTree.target = $('#layout_west_tree');
        if ($.mainpage.westTree.target.isEasyUI("tree")) {
            return;
        }
        $.mainpage.westTree.target.tree({
            animate: true,
            lines: false,
            toggleOnDblClick: true,
            selectOnContextMenu: true,
            toggleMenu: {
                submenu: false
            },
            onClick: function (node) {
                $.mainpage.addModuleTab(node);
            },
            onLoadSuccess: function (node, data) {
                $.mainpage.instTreeStatus($.mainpage.westTree.target);
            },
            contextMenu: [{
                text: "打开/转到",
                iconCls: "icon-standard-application-add",
                disabled: function (e, node) {
                    return !((node.attributes && node.attributes.href) || node.src);
                },
                handler: function (e, node) {
                    $.mainpage.addModuleTab(node);
                }
            }, "-", {
                text: "添加至个人收藏",
                iconCls: "icon-standard-feed-add",
                disabled: function (e, node) {
                    return !$.mainpage.westTree.target.tree("isLeaf", node.target) || !$.mainpage.favoTree.checkInCookie(node.id);
                },
                handler: function (e, node) {
                    $.mainpage.westTree.addFavo(node);
                }
            }]
        });
    };
    $.mainpage.mainTabs.select = function (title, index) {
        var westPanel = centerLayout.layout('panel', 'west');
        if (index == 1) {
            westPanel.panel('setTitle', title);
            var nodeData = $.cookie("easyuiFavoTreeData");
            nodeData = nodeData ? $.util.parseJSON(nodeData) : [];
            $('#layout_west_favoTree').tree('loadData', nodeData);
        } else {
            westPanel.panel('setTitle', $.mainpage.westTree.panelTitle);
        }
    };
    $.mainpage.westTree.addFavo = function (node) {
        var treeId = $.cookie("easyuiFavoTreeId");
        treeId = treeId ? treeId : "";
        treeId = treeId.split(',');
        if (!$.array.contains(treeId, node.id)) {
            var treeData = $.cookie("easyuiFavoTreeData");
            treeData = treeData ? $.util.parseJSON(treeData) : [];
            var newNode = {};
            newNode.id = node.id;
            newNode.href = node.src ? node.src : node.href ? node.href : node.url ? node.url : "";
            newNode.text = node.text;
            newNode.iconCls = node.iconCls;
            treeData.push(newNode);
            treeId.push(node.id);
            $.cookie("easyuiFavoTreeData", JSON.stringify(treeData));
            $.cookie("easyuiFavoTreeId", treeId.join(','));
        }
    };

    $.mainpage.favoTree.checkInCookie = function (nodeId) {
        var treeId = $.cookie("easyuiFavoTreeId");
        treeId = treeId ? treeId : "";
        treeId = treeId.split(',');
        return !$.array.contains(treeId, nodeId);

    };

    $.mainpage.favoTree.initTree = function () {
        var t = $('#layout_west_favoTree');
        if (t.isEasyUI("tree")) {
            return;
        }
        var nodeData = $.cookie("easyuiFavoTreeData");
        nodeData = nodeData ? $.util.parseJSON(nodeData) : [];
        t.tree({
            animate: true,
            lines: false,
            toggleOnDblClick: true,
            selectOnContextMenu: true,
            moveMenu: true,
            data: nodeData,
            onClick: function (node) {
                $.mainpage.addModuleTab(node);
            },
            onLoadSuccess: function (node, data) {
                $.mainpage.instTreeStatus(t);
            },
            contextMenu: [{
                text: "打开/转到",
                iconCls: "icon-standard-application-add",
                disabled: function (e, node) {
                    return !((node.attributes && node.attributes.href) || node.src);
                },
                handler: function (e, node) {
                    $.mainpage.addModuleTab(node);
                }
            }, "-", {
                text: "添加",
                iconCls: "icon-cologne-plus",
                handler: function (e, node) {
                    $.mainpage.favoTree.add(t, node);
                }
            }, {
                text: "重命名",
                iconCls: "icon-hamburg-pencil",
                handler: function (e, node) {
                    t.tree("beginEdit", node.target);
                }
            }, {
                text: "移除",
                iconCls: "icon-standard-application-go",
                handler: function (e, node) {
                    $.mainpage.favoTree.remove(t, node);
                }
            }, "-", {
                text: "刷新",
                iconCls: "icon-cologne-refresh",
                handler: function (e, node) {
                    var url = $(t).tree('options').url;
                    $.mainpage.favoTree.loadData(url);
                }
            }],
            onAfterEdit: function (node) {
                $.mainpage.favoTree.rname(t);
            },
            onDrop: function (target, source, point) {
                $.mainpage.favoTree.drop(t, target, source, point);
            }
        });
    };

    $.mainpage.favoTree.rname = function (t) {
        var treeData = $(t).tree('getRoots');
        $.cookie("easyuiFavoTreeData", JSON.stringify(treeData));
    };

    $.mainpage.favoTree.remove = function (t, node) {
        $.messager.confirm('确认信息', '您确认想要移除此条收藏吗？', function (r) {
            if (r) {
                t.tree("remove", node.target);
                var treeData = $(t).tree('getRoots');
                $.cookie("easyuiFavoTreeData", JSON.stringify(treeData));
            }
        });
    };

    $.mainpage.favoTree.add = function (target, node) {
        var dialog = $.easyui.showDialog({
            title: "添加收藏",
            width: 500,
            height: 185,
            maximizable: true,
            href: $.util.getRootPath() + '/rsframe/page/layout/add_favo.html',
            topMost: true,
            saveButtonText: '确定',
            onSave: function () {
                var node = {
                    id: $.util.guid(),
                    text: parent.$('#title').val(),
                    type: 1,
                    href: parent.$('#address').val(),
                    iconCls: parent.$('#iconCls').comboicons('getValue')
                };
                $(target).tree('insert', {
                    after: node.target,
                    data: node
                });
                var treeData = $(target).tree('getRoots');
                $.cookie("easyuiFavoTreeData", JSON.stringify(treeData));
                dialog.dialog('close');
            }
        });
    };

    $.mainpage.favoTree.drop = function (t, target, source, point) {
        var treeData = $(t).tree('getRoots');
        $.cookie("easyuiFavoTreeData", JSON.stringify(treeData));
    };

    //加载西边收藏panel的tree
    $.mainpage.favoTree.loadData = function (option) {
        if ($.array.isArray(option)) {
            $('#layout_west_favoTree').tree('loadData', option);
        } else if ($.string.isUrl(option)) {
            $.util.post(option, function (data) {
                if (!data.success) {
                    $.easyui.messager.show("提示消息", data.message, "info");
                    return;
                }
                $('#layout_west_favoTree').tree('loadData', data.items);
            });
        }
    };
    $.mainpage.instTreeStatus = function (target) {
        var t = $(target), array = t.tree("getRoots");
        $.each(array, function (i, n) {
            var cc = t.tree("getChildren", n.target);
            t.tree("expand", n.target);
            $.each(cc, function (l, c) {
                t.tree("collapseAll", c.target);
            });
        });
    };

    $.mainpage.westTree.removeWestPanel = function (data) {
        centerLayout.layout('remove', 'west');
    };

    //加载西边panel的tree
    $.mainpage.westTree.loadWestTree = function (data) {
        var westPanel = centerLayout.layout('panel', 'west');
        if (westPanel.length == 0) {
            centerLayout.layout('add', {
                region: 'west',
                iconCls: 'icon-menu',
                width: 170,
                minWidth: 170,
                maxWidth: 350,
                border: false,
                title: '导航菜单',
                split: true,
                tools: [{
                    iconCls: 'icon-line-spacing',
                    handler: function () {
                        $.mainpage.westTree.collapseOrExpand(this);
                    }
                }],
                onLoad: function () {
                    $.mainpage.westTree.initTree();
                    $.mainpage.favoTree.initTree();
                    $('#layout_west_tree').tree('loadData', data);
                }
            });
            centerLayout.layout('panel', 'west').panel('refresh', $.util.getRootPath() + '/rsframe/page/layout/west.html');
        } else {
            $('#layout_west_tree').tree('loadData', data);
        }
    };

    $.mainpage.changeTheme = function (themeName) {
        var loadingIndicator = $("#loading-indicator").show();
        $.mainpage.setTheme(themeName, true);
        loadingIndicator.hide();
    };
    //  设置当前系统主界面的界面皮肤风格；该方法提供如下参数：
    //      theme:      界面皮肤风格名称
    //      setCookie:  可选参数，boolean 类型，表示是否将 theme 保存至 cookie 名为 themeName
    $.mainpage.setTheme = function (theme, setCookie) {
        if (setCookie == null || setCookie == undefined) {
            setCookie = true;
        }
        $.easyui.theme(true, theme, function (item) {
            if (setCookie) {
                $.cookie("easyuiTheme", theme, {
                    expires: 360 * 10
                });
                var msg = $.string.format("您设置了新的系统主题皮肤为：{0}，{1}。", item.name, item.path);
                setTimeout(function () {
                    $.easyui.messager.show(msg);
                }, 100);
            }
        });
        $.mainpage.setThemeIcon(theme);
    };

    $.mainpage.setThemeIcon = function (theme) {
        var themeName = theme ? theme : $.cookie("easyuiTheme");
        themeName = themeName ? themeName : 'rs-default';
        var mainThemeMenuE = $('#mainThemeMenu');
        var mainThemeMenuClass = mainThemeMenuE.find('.mainThemeMenu');
        mainThemeMenuClass.each(function () {
            var name = $(this).attr('name');
            var themeText = $.string.trim($(this).text());
            var item = mainThemeMenuE.menu('findItem', themeText);
            if (themeName == name) {
                if (item) {
                    mainThemeMenuE.menu('setIcon', {
                        target: item.target,
                        iconCls: 'icon-ok'
                    });
                }
            } else {
                if (item) {
                    mainThemeMenuE.menu('setIcon', {
                        target: item.target,
                        iconCls: 'empty'
                    });
                }
            }
        });
    };

    $.mainpage.mainTabs.updateHash = function (index) {
        var opts = $(mainTabs).tabs("getTab", index).panel("options");
        window.location.hash = opts.href ? opts.href : "";
    };

    $.mainpage.westTree.collapseOrExpand = function (aEl) {
        var identity = $(aEl).attr('identity');
        if (identity == 0) {
            $('#layout_west_tree').tree('expandAll');
            $(aEl).attr({
                'identity': '1'
            });
        } else {
            $(aEl).attr({
                'identity': '0'
            });
            $('#layout_west_tree').tree('collapseAll');
        }
    };
    //放大或重置中部窗口
    $.mainpage.mainTabs.fullScreenInOut = function (target) {
        var elName = target < 10 ? target : $(target).attr('name');
        if (elName == 0) {
            $(target).attr({
                name: 1
            });
            $("#mainpage_layout").layout("unFull");
            centerLayout.layout('expand', 'west');
        } else if (elName == 1) {
            $(target).attr({
                name: 0
            });
            $("#mainpage_layout").layout("full");
            centerLayout.layout('collapse', 'west');
        }
    };
    //全屏或重置窗口
    $.mainpage.fullScreenInOut = function () {
        if ($.util.supportsFullScreen) {
            if ($.util.isFullScreen()) {
                $.util.cancelFullScreen();
            } else {
                $.util.requestFullScreen();
            }
        } else {
            var msg = "您的浏览器不支持全屏API哦，请更换至最新的 Chrome/Firefox/Safari 浏览器或通过 F11快捷键进行操作！";
            $.easyui.messager.show('提示消息', msg, 'info');
        }
    };
    //检测浏览器版本进行相应提示
    $.mainpage.checkBrowser = function () {
        var hintMsg;
        if (navigator.userAgent.indexOf('MSIE') > -1) {
            if (navigator.userAgent.indexOf('MSIE 7') > -1) {
                hintMsg = '您使用的浏览器为“IE7”，版本过低，可能会在使用过程中出现未知兼容性异常；<br/>为避免影响您的使用，请使用“IE8”以上版本浏览器或其他内核的浏览器。';
            } else if (navigator.userAgent.indexOf('MSIE 6') > -1) {
                hintMsg = '您使用的浏览器为“IE6”，版本过低，可能会在使用过程中出现未知兼容性异常；<br/>为避免影响您的使用，请使用“IE8”以上版本浏览器或其他内核的浏览器。';
            }
        }
        if (hintMsg) {
            setTimeout(function () {
                $.messager.show({
                    title: '提示消息',
                    width: 240,
                    height: 130,
                    timeout: 10000,
                    msg: hintMsg
                });
            }, 100);
        }
    };
    //向北边工具栏添加内容
    $.mainpage.southPanel.innerHTML = function (html) {
        $('#layout_south_panel_div').html(html);
    };
    //向南边面板添加内容
    $.mainpage.southPanel.innerHTML = function (html) {
        $('#layout_south_panel_div').html(html);
    };
    //刷新南边面板来装载远程数据
    $.mainpage.southPanel.refresh = function (href) {
        if ($.string.isUrl(href)) {
            $('#layout_south_panel_div').load(href);
        } else {
            $.easyui.messager.show("错误提醒", "southPanel的Href不是合法URL，如果该问题重复出现，请联系您的系统管理员并反馈该故障。", "error");
        }
    };
    //初始化页面布局
    $.mainpage.layout.init = function () {
        centerLayout = $('#layout_center_layout');
        $('#mainpage_layout').layout('panel', 'north').panel('refresh', $.util.getRootPath() + '/rsframe/page/layout/north.html');
        $.util.exec(function () {
            setTimeout(function () {
                $.mainpage.setThemeIcon();
            }, 500);
            centerLayout.layout('panel', 'center').panel('refresh', $.util.getRootPath() + '/rsframe/page/layout/center.html');
        });
    };
    $.easyui.loading({
        msg: "正在处理中，请稍等...",
        locale: "#loading-indicator",
        topMost: true
    });
    $.util.exec(function () {
        $.mainpage.layout.init();
        $.mainpage.checkBrowser();
    });
    $.util.exec(function () {
        $("#loading-indicator").hide();
    }, 100);
});
